package priv.xp.androidexample

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StrictMode
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import priv.xp.androidexample.databinding.FragmentCameraBinding
import java.io.File

@Route(path = "/camera/fragment")
class CameraFragment : Fragment() {
    private lateinit var binding: FragmentCameraBinding

    private val cameraActivity =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            context?.let {
                val bmp: Bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    val src = ImageDecoder.createSource(it.contentResolver, Uri.fromFile(file))
                    ImageDecoder.decodeBitmap(src)
                } else {
                    MediaStore.Images.Media.getBitmap(it.contentResolver, Uri.fromFile(file))
                }

                binding.imgCamera.setImageBitmap(bmp)
            }
        }

    private val file: File by lazy {
        File(this.context?.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "tmp.jpg")
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentCameraBinding.inflate(inflater, container, false)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val builder = StrictMode.VmPolicy.Builder()
            StrictMode.setVmPolicy(builder.build())
            builder.detectFileUriExposure()
        }

        binding.fab.setOnClickListener {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file))
            cameraActivity.launch(intent)
        }

        return binding.root
    }
}
